<?php
namespace app\common\service;

use app\common\model\JobModel;
use app\index\model\UserModel;
use notification\tools\EmailNotification;
use notification\tools\WeWorkNotification;
use notification\tools\DingdingNotification;

class NoticeService{

    public $noticeChannel = [];

    private $user = [];


    public function __construct(UserModel $user)
    {
        $this->user = $user;
        // if($user->email){
        //     $this->noticeChannel['email'] = new EmailNotification();
        // }

        // if($user->userId){
        //     $corp_id = config('wework.corp_id');
        //     $agent_id = config('wework.agent_id');
        //     $secret = config('wework.secret');

        //     $this->noticeChannel['userId'] = new WeWorkNotification($corp_id, $agent_id, $secret);
        // }

        if($user->dingUserId){
            $agent_id = config('dingding.agent_id');
            $appkey = config('dingding.appkey');
            $appsecret = config('dingding.appsecret');
            $this->noticeChannel['dingUserId'] = new DingdingNotification($appkey, $appsecret, $agent_id);
        }
    }

    public function sendText($title, $content) {
        $result = [];
        $message = new \notification\message\Message($title, $content);

        foreach($this->noticeChannel as $key => $channel){
            try {
                $result[$key] = $channel->sendText($message, $this->user[$key]);
            } catch (\Exception $e) {
                $result[$key] = $e->getMessage();
            }
        }
        return $result;
    }



    public function noticeJobHandle($job, $operation_note) {
        $result = [];
        $title = sprintf("%s-%s", $job['name'], JobModel::getJobNoticeTitle($job['status']));

        $content = sprintf(
            "## %s\n * 任务发布人：%s\n* 任务执行人：%s\n* 客户姓名：%s\n* 当前状态：%s \n * 操作时间: %s\n* 操作备注: %s\n\n[查看任务详情](%s)", 
            $title, 
            $job->job_add_user->name, 
            $job->job_exec_user->name,
            $job->customer->name,
            $job->job_status_info['info'],
            date('Y-m-d H:i:s'),
            $operation_note,
            "http://boyi.tinyask.cn/#/job/detail/{$job->id}"
        );

        $message = new \notification\message\Message($title, $content);
        foreach($this->noticeChannel as $key => $channel){
            try {
                $result[$key] = $channel->sendText($message, $this->user[$key]);
            } catch (\Exception $e) {
                $result[$key] = $e->getMessage();
            }
        }
        return $result;
    }
}